package com.mes.biz.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mes.biz.domain.*;
import com.mes.biz.domain.vo.BizCostVo;
import com.mes.biz.mapper.BizCostMapper;
import com.mes.biz.mapper.BizCustomerMapper;
import com.mes.biz.mapper.BizCustomerPayableMapper;
import com.mes.biz.service.BizCostDetailService;
import com.mes.biz.service.BizCostService;
import com.mes.biz.service.BizCustomerPayableDetailService;
import com.mes.biz.service.BizCustomerPayableService;
import com.mes.common.core.domain.BaseEntity;
import com.mes.common.core.page.PageDomain;
import com.mes.common.core.service.BaseServiceImpl;
import com.mes.common.utils.SecurityUtils;
import com.mes.common.utils.StringUtils;
import com.mes.common.utils.sql.SqlUtil;
import org.apache.commons.compress.utils.Sets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Random;
import java.util.Set;

/**
 * 收支单Service业务层处理
 * @author wy
 * @email wy
 * @date 2023-08-25
 */
@Service
@Transactional(readOnly = true)
public class BizCostServiceImpl extends BaseServiceImpl<BizCostMapper, BizCost> implements BizCostService {

    private static final Logger log = LoggerFactory.getLogger(BizCostServiceImpl.class);


    @Resource
    private BizCostDetailService bizCostDetailService;
    @Resource
    private BizCustomerPayableMapper bizCustomerPayableMapper;
    @Resource
    private BizCustomerPayableDetailService bizCustomerPayableDetailService;
    @Resource
    private BizCustomerPayableService bizCustomerPayableService;
    @Resource
    private BizCustomerMapper bizCustomerMapper;
    /**
     * 获取单条数据
     * @param bizCost 收支单
     * @return 收支单
     */
    @Override
    public BizCost get(BizCost bizCost) {
        BizCost dto = super.get(bizCost);
        return dto;
    }

    /**
     * 获取单条数据
     * @param id 收支单id
     * @return 收支单
     */
    @Override
    public BizCost get(String id) {
        BizCost dto = super.get(id);
        return dto;
    }

    /**
     * 查询收支单列表
     * @param bizCost 收支单
     * @return 收支单
     */
    @Override
    public List<BizCost> findList(BizCost bizCost) {
		List<BizCost> bizCostList = super.findList(bizCost);
        return bizCostList;
    }

    /**
     * 分页查询收支单列表
     * @param bizCost 收支单
     * @return 收支单
     */
    @Override
    public PageInfo<BizCost> findPage(BizCost bizCost) {
		PageInfo<BizCost> page = super.findPage(bizCost);
        return page;
    }

    /**
     * 保存收支单
     * @param bizCost
     * @return 结果
     */
    @Override
    public boolean save(BizCost bizCost) {
        return super.save(bizCost);
    }

    /**
     * 删除收支单信息
     * @param bizCost
     * @return 结果
     */
    @Override
    public boolean remove(BizCost bizCost) {
        return super.remove(bizCost);
    }

    /**
     * 批量删除收支单
     * @param ids 需要删除的收支单ID
     * @return 结果
     */
    @Transactional(readOnly = false)
    @Override
    public int deleteBizCostByIds(String[] ids) {
        return mapper.deleteBizCostByIds(ids, BaseEntity.DEL_FLAG_DELETE);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveCost(BizCost bizCost) {
        Random random = new Random();
        //把随机生成的数字转成字符串
        String str = String.valueOf(random.nextInt(9));
        for (int i = 0; i < 5; i++) {
            str += random.nextInt(9);
        }
        bizCost.setPayCode("SZD-" + str);
        String tenantId = SecurityUtils.getTenantId();
        bizCost.setTenantId(tenantId);
        boolean res = save(bizCost);
        if(res) {
            List<BizCostDetail> bizCostDetailList = bizCost.getBizCostDetailList();
            for (BizCostDetail bizCostDetail : bizCostDetailList) {
                //新增明细
                bizCostDetail.setPaymentId(bizCost.getId());
                bizCostDetail.setTenantId(tenantId);
                bizCostDetailService.save(bizCostDetail);
            }
        }
        return res;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateCost(BizCost bizCost) {
        boolean res = save(bizCost);
        if(res) {
            Set<String> existsSets = Sets.newHashSet();
            List<BizCostDetail> costDetailList = bizCostDetailService.selectByCostId(bizCost.getId());

            if (costDetailList !=null && costDetailList.size()>0){
                costDetailList.forEach(existsVO -> {
                    existsSets.add(existsVO.getId());
                });
            }

            List<BizCostDetail> bizCostDetailList = bizCost.getBizCostDetailList();
            if (bizCostDetailList != null && bizCostDetailList.size() > 0) {
                for (BizCostDetail bizCostDetail : bizCostDetailList){
                    bizCostDetail.setPaymentId(bizCost.getId());
                    bizCostDetail.setTenantId(bizCost.getTenantId());
                    existsSets.remove(bizCost.getId());
                    bizCostDetailService.save(bizCostDetail);
                }
            }
            if (existsSets.size()>0){
                String[] ids = existsSets.toArray(new String[0]);
                bizCostDetailService.deleteBizCostDetailByIds(ids);
            }
        }
        return res;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean auditCost(String id) {
        BizCost bizCost = super.get(id.split(":")[0]);
        bizCost.setStatus((id.split(":")[1]));
        int update = mapper.update(bizCost);
        if(update > 0) {
            if ("1".equals(bizCost.getStatus())) {
                //修改客户应收账款
                if (StringUtils.isNotEmpty(bizCost.getCustomerId())){
                    BizCustomer bizCustomer = bizCustomerMapper.get(bizCost.getCustomerId());
                    BizCustomerPayable bizCustomerPayable = bizCustomerPayableMapper.getBizCustomerPayableByCustomerId(bizCost.getCustomerId());
                    if (bizCustomerPayable != null){
                        bizCustomerPayable.setTotalAmount(bizCustomerPayable.getTotalAmount().add(bizCost.getPayAmount()));
                        bizCustomerPayable.setHasAmount(bizCustomerPayable.getTotalAmount().subtract(bizCustomerPayable.getPayAmount()));
                    }else {
                        Random random = new Random();
                        String str = String.valueOf(random.nextInt(9));
                        for (int i = 0; i < 5; i++) {
                            str += random.nextInt(9);
                        }
                        bizCustomerPayable=new BizCustomerPayable();
                        bizCustomerPayable.setPayableCode("YSZK" + str);
                        bizCustomerPayable.setCustomerId(bizCost.getCustomerId());
                        bizCustomerPayable.setCustomerName(bizCustomer.getCustomerName());
                        bizCustomerPayable.setTotalAmount(bizCost.getPayAmount());
                        bizCustomerPayable.setPayAmount(BigDecimal.ZERO);
                        bizCustomerPayable.setTenantId(bizCost.getTenantId());
                        bizCustomerPayable.setHasAmount(bizCustomerPayable.getPayAmount());
                    }
                    bizCustomerPayableService.save(bizCustomerPayable);

                    List<BizCostDetail> costDetailList = bizCostDetailService.selectByCostId(bizCost.getId());
                    if (costDetailList !=null && costDetailList.size()>0){
                        for (BizCostDetail bizCostDetail:costDetailList){
                            BizCustomerPayableDetail detail =new BizCustomerPayableDetail();
                            detail.setOrderProductId(bizCostDetail.getId());
                            detail.setCustomerId(bizCost.getCustomerId());
                            detail.setOrderNumber(bizCost.getPayCode());
                            detail.setTenantId(bizCost.getTenantId());
                            detail.setTotalAmount(bizCostDetail.getPayAmount());
                            detail.setPayAmount(BigDecimal.ZERO);
                            detail.setType("1");
                            detail.setRemark(bizCostDetail.getRemark());
                            bizCustomerPayableDetailService.save(detail);
                        }
                    }
                }
            }else {
                //反审核 修改金额
                if (StringUtils.isNotEmpty(bizCost.getCustomerId())){
                    BizCustomerPayable bizCustomerPayable = bizCustomerPayableMapper.getBizCustomerPayableByCustomerId(bizCost.getCustomerId());
                    bizCustomerPayable.setTotalAmount(bizCustomerPayable.getTotalAmount().subtract(bizCost.getPayAmount()));
                    bizCustomerPayable.setHasAmount(bizCustomerPayable.getTotalAmount().subtract(bizCustomerPayable.getPayAmount()));
                    bizCustomerPayableMapper.update(bizCustomerPayable);
                }
                List<BizCostDetail> costDetailList = bizCostDetailService.selectByCostId(bizCost.getId());
                if (costDetailList !=null && costDetailList.size()>0) {
                    for (BizCostDetail bizCostDetail : costDetailList) {
                        //删除应收账款
                        bizCustomerPayableDetailService.deleteByOderProductId(bizCostDetail.getId(),bizCost.getPayCode());
                    }
                }
            }
        }
        return update>0;
    }

    @Override
    public PageInfo<BizCostVo> listStatPage(BizCost bizCost) {
        PageDomain page = bizCost.getPage();
        Integer pageNum = page.getPageNum();
        Integer pageSize = page.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize))
        {
            String orderBy = SqlUtil.escapeOrderBySql(page.getOrderBy());
            Boolean reasonable = page.getReasonable();
            PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
        }
        bizCost.setTenantId(SecurityUtils.getTenantId());
        return new PageInfo(mapper.listStat(bizCost));
    }

    @Override
    public List<BizCostVo> listStat(BizCost bizCost) {
        return mapper.listStat(bizCost);
    }
}
